package com.adam.springsecurity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.util.AntPathMatcher;

import java.util.function.Supplier;

@Slf4j
public class MyAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    private int i = 0;
    private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
        String requestURI = object.getRequest().getRequestURI();
        //检查是否是remember-me登录
        log.info("MyAuthorizationManager check starts requestURI={} rememberMe={}", requestURI, trustResolver.isRememberMe(authentication.get()));
        i++;
        boolean grant = i % 2 == 0;
        return new AuthorizationDecision(grant);
    }

    public static void main(String[] args) {
        AntPathMatcher matcher = new AntPathMatcher();
        System.out.println(matcher.match("/projects/**", "/projects"));
        System.out.println(matcher.match("/projects/**", "/projects/123"));
    }

}
